from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField, IntegerField, SelectField, BooleanField
from wtforms.validators import Length, DataRequired, Optional,ValidationError
from ....models import Category, BanWords
from flask import Markup


class SearchForm(FlaskForm):
    check = BooleanField('仅查看待审核文章')
    category_id = SelectField('栏目')
    title = StringField('标题')
    search = SubmitField('搜索')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.category_id.choices = [(0, '栏目筛选')]
        for item in Category.html_tree():
            length = len(item.level.split('-'))
            if length == 1:
                _str = ''
            elif length == 2:
                _str = '&nbsp;&nbsp;&nbsp;'
            else:
                _str = '&nbsp;&nbsp;&nbsp;' * (length - 1)
            self.category_id.choices.append(
                (
                    item.id,
                    Markup(_str + item.mark + item.title)
                )
            )


class EditForm(FlaskForm):
    title = StringField('标题', validators=[
        Length(min=1, max=64, message='标题长度1~64之间')
    ])
    source = StringField('文章来源', validators=[
        Optional(),
        Length(min=2, max=16, message='来源长度2-16之间')
    ])
    author = StringField('作者', validators=[
        Optional(),
        Length(min=1, max=16, message='作者长度1-16之间')
    ])
    original_title = StringField('原标题', validators=[
        Optional(),
        Length(min=1, max=64, message='原标题长度1~64之间')
    ])
    keyword = StringField('关键词', validators=[
        Optional(),
        Length(min=1, max=64, message='关键词长度2~64之间')
    ])
    description = TextAreaField('内容摘要', render_kw={"rows": "3"}, validators=[
        Optional(),
        Length(min=2, max=128, message='摘要长度2~100之间')
    ])
    thumbnail = StringField('缩略图', validators=[
        Optional(),
        Length(min=5, max=128, message='图片链接长度5-128之间')
    ])
    tags = TextAreaField('TAGS', validators=[
        Length(min=0, max=128, message='标签总长度不能超128字符')
    ])
    category_id = SelectField('发布栏目', coerce=int)
    top = BooleanField('头条')
    focus = BooleanField('焦点图')
    good = BooleanField('推荐')
    hot = IntegerField('阅读量')
    content = TextAreaField('内容', validators=[
        Length(min=1, message='正文内容必须')
    ])

    save = SubmitField('发布')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ban_words = BanWords.query.filter_by(status=True).all()
        self.category_id.choices = []
        for item in Category.html_tree():
            length = len(item.level.split('-'))
            if length == 1:
                _str = ''
            elif length == 2:
                _str = '&nbsp;&nbsp;&nbsp;'
            else:
                _str = '&nbsp;&nbsp;&nbsp;' * (length - 1)
            self.category_id.choices.append(
                (
                    item.id,
                    Markup(_str + item.mark + item.title)
                )
            )

    def validate_original_title(self, field):
        check, ban = self.check(field)
        if check:
            raise ValidationError('原标题中出现了如下违禁词: "{}"'.format(ban))

    def validate_content(self, field):
        check, ban = self.check(field)
        if check:
            raise ValidationError('正文中不能出现如下违禁词: "{}"'.format(ban))

    def validate_title(self, field):
        check, ban = self.check(field)
        if check:
            raise ValidationError('标题中不能出现如下违禁词: "{}"'.format(ban))

    def validate_keyword(self, field):
        check, ban = self.check(field)
        if check:
            raise ValidationError('关键词中不能出现如下违禁词: "{}"'.format(ban))

    def validate_description(self, field):
        check, ban = self.check(field)
        if check:
            raise ValidationError('描述中不能出现如下违禁词: "{}"'.format(ban))

    def check(self, f):
        check = False
        ban = set()
        for item in self.ban_words:
            if item.ban_word in f.data:
                check = True
                ban.add(item.ban_word)
        return check, ",".join(ban)
